#!/usr/bin/env python3
from aliyunsdkcore.client import AcsClient
from aliyunsdkcore.acs_exception.exceptions import ClientException
from aliyunsdkcore.acs_exception.exceptions import ServerException
from aliyunsdkcdn.request.v20180510.RefreshObjectCachesRequest import RefreshObjectCachesRequest
# pip install aliyun-python-sdk-cdn
import json
import sys
from configs import ALIYUN_CONFIG


class PushCdn(object):
    def __init__(self, accessid, secert, area, url):
        self.__accessid = accessid
        self.__secert = secert
        self.__url = url
        self.acessdir = "Directory"
        self.area = area

    def Flush_Dir(self):
        try:
            client = AcsClient(self.__accessid, self.__secert, self.area)
            request = RefreshObjectCachesRequest()
            request.set_accept_format("json")
            request.set_ObjectPath("http://{0}/".format(self.__url))
            request.set_ObjectType(self.acessdir)  # 指定为目录刷新，默认URL刷新
            response = client.do_action_with_exception(request)
            datadict = json.loads(response.decode('utf-8'))
            print(datadict)
        except Exception as e:
            print("请求失败:　%s" % e)


if __name__ == '__main__':
    area = sys.argv[1]  # me-east-1
    url = sys.argv[2]  # http://test-hotdown.zsjae.com/
    aliyun = ALIYUN_CONFIG['aliyun_prod']
    CDN = PushCdn(aliyun['id'],
                  aliyun['key'], area, url)
    CDN.Flush_Dir()
